<template autoRoute="true">
  <button @click="dragFn">切换drag</button>
  <div class="wbs-container">
    <CLTabsWbs
      v-model="activeTab"
      :items="tabItems"
      @tab-added="handleTabAdded"
      @tab-removed="handleTabRemoved"
      @tab-sorted="handleTabSorted"
      @tab-activated="handleTabActivated"
    >
      <template #content="{ activeTab: tabItem }">
        <div v-if="tabItem && tabItem.id === 1">
          <Design />
        </div>
        <div v-if="tabItem && tabItem.id === 2">
          <!-- 封装的Toolbar组件 -->
          <CToolbar
            :fields="fields"
            :visibleButtons="toolbarOptions"
            :search-fields="['name']"
            @updateFieldVisibility="updateFieldVisibility"
            @updateField="updateField"
            @fieldReordered="handleFieldReordered"
            @lineHeightChanged="handleLineHeightChanged"
            @search="handleSearch"
            @filter="handleFilter"
            @sort="handleSort"
            @openAddRecordDialog="handleAddRecordDialog"
          />

          <!-- 任务树形结构 -->
          <div class="wbs-tree-container">
            <!-- 批量操作浮层 (使用封装的组件) -->
            <CLBatchOpToolbar
              :show="showCLBatchOpToolbar"
              :selected-count="selectedRecords.length"
              @delete="handleBatchDelete"
            >
              <button class="batch-btn" @click="handleModifyProperties">
                修改属性
              </button>
              <button class="batch-btn" @click="handleModifyType">
                修改类型
              </button>
            </CLBatchOpToolbar>
            <CLTable
              ref="cTableTaskRef"
              :fields="fields as any"
              :initial-data="tableData"
              :line-height="currentLineHeight"
              :router-fields="routerFields"
              :tableConfig="tableConfig"
              :more-actions="moreActions"
              :on-add-node="handleAddNode"
              :on-delete-node="handleDeleteNode"
              :on-update-node="handleUpdateNode"
              :statusOptions="statusOptions"
              @update:initial-data="updateTableData"
              @update:saveField="updateTableData"
              @show:records="handleShowRecords"
              @onMoreAction="handleMoreAction"
              @pagerChange="pagerChange"
              @drag-completed="handleDragCompleted"
            />
          </div>
          <!-- 字段配置悬浮层 -->
          <FieldConfigPopup
            :fields="currentFields"
            :position="fieldConfigPosition"
            :visible="showFieldConfig"
            @close="showFieldConfig = false"
            @fieldsChange="handleFieldsChange"
          />
        </div>
        <div v-if="tabItem && tabItem.id === 3">
          <!-- 任务树形结构 -->
          <div class="wbs-tree-container">
            <!-- 批量操作浮层 -->
            <CLBatchOpToolbar
              :show="showCLBatchOpToolbarGantt"
              :selected-count="selectedRecords.length"
              @delete="handleBatchDelete"
            >
              <button class="batch-btn">修改属性</button>
              <button class="batch-btn">修改类型</button>
            </CLBatchOpToolbar>
            <div>
              <div class="gantt-time-btns">
                <button
                  class="gantt-time-btn"
                  :class="{ active: currentViewMode === 'week' }"
                  @click="changeColWidth('week')"
                >
                  周
                </button>
                <button
                  class="gantt-time-btn"
                  :class="{ active: currentViewMode === 'mouth' }"
                  @click="changeColWidth('mouth')"
                >
                  月
                </button>
              </div>
              <CLTable
                ref="clTableRef"
                :fields="fields"
                :initial-data="tableData"
                :initial-links="tableLinks"
                :timeScalesToShow="['day', 'month']"
                :line-height="currentLineHeight"
                :router-fields="routerFields"
                :more-actions="moreActions"
                :tableConfig="ganttConfig"
                :on-add-node="handleAddNode"
                :on-delete-node="handleDeleteNode"
                :on-update-node="handleUpdateNode"
                @update:initial-data="updateTableData"
                @update:saveField="updateTableData"
                @view-node-detail="handleShowRecordDetail"
                @show:records="handleShowRecords"
                @node-selected="handleNodeSelected"
                @onMoreAction="handleMoreAction"
              />
            </div>
          </div>
        </div>
        <div v-if="tabItem && tabItem.id === 4">
          <DataReport
            :fields="reportFields"
            :tableData="reportTableData"
            :tree-menu-data="reportMenuData"
            :more-actions="reportMoreActions"
            :toolbar-options="reportToolbarOptions"
            :router-fields="reportRouterFields"
            :table-config="reportTableConfig"
          />
        </div>
      </template>
    </CLTabsWbs>
    <div class="add-record-dialog-container">
      <AddRecordDialog
        v-if="drawerDisplay"
        :size="showAddRecordDialog"
        :fields="fields"
        :record="selectedRecord"
        :routerFields="dialogRouterFields"
        @close:size="closeRecordDialog"
        @update:formData="updateRecord"
      />
    </div>
  </div>
  <ModifyDialog
    :visible="showBatchModifyDialog"
    :dialog-type="batchModifyType"
    :selected-count="selectedRecords.length"
    :target-type="targetType"
    :fields="batchModifyFields as any"
    @confirm="handleBatchModifyConfirm"
    @cancel="handleBatchModifyCancel"
    @close:modify="handleBatchModifyClose"
  />
  <FormPopup
    :title="title"
    :selector-visible="popup"
    :fields="fields"
    :table-data="popupTable"
    :table-config="userTableConfig"
    :router-fields="neededFieldNames"
    :current-assignee="changeUserName"
    @update:selectorVisible="popup = $event"
    @selector:nodes="handleMoreAction"
  />
</template>

<script lang="ts" setup>
  import { ref, onMounted, provide, reactive } from "vue";

  import CLTabsWbs from "@/components/CLTabsWbs.vue";
  import CToolbar from "@/components/CToolbar.vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import Design from "@/views/design/ProjectOverview.vue";
  import { otherIcon, tableIcon } from "@/utils/SvgIcons.ts";
  import {
    mockFieldsProjectResponse,
    type TabItem,
    type DynamicField,
  } from "@/data/wbsFields.ts";
  import { mockFieldsResponse } from "@/data/wbsFields.ts";
  import {
    optionsData,
    type ProjectNode,
    projectSampleData,
    tmpLinks,
  } from "@/data/wbsData.ts";
  import AddRecordDialog from "@/components/AddRecordDialog.vue";
  import ModifyDialog from "@/views/pm/wbs/ModifyDialog.vue";
  import FormPopup from "@/components/FormPopup.vue";
  import {
    getTableHeaderByTargetType,
    listTask,
    updateTask,
  } from "@/api/project";
  import { useRoute } from "vue-router";
  import type { QueryCondition, SortParam } from "@/interface/project";
  import DataReport from "@/views/demo/wbs/dataReport/DataReport.vue";
  import { mockFields } from "@/views/demo/data/fields.ts";
  import { mockData, treeData } from "@/views/demo/data/data.ts";

  // 标签页数据
  const activeTab = ref<number>(1);
  const tabItems = ref<TabItem[]>([
    {
      id: 1,
      title: "项目概览",
      icon: otherIcon,
      closable: false,
    },
    {
      id: 2,
      title: "任务列表",
      icon: tableIcon,
      closable: false,
    },
    {
      id: 3,
      title: "甘特视图",
      icon: tableIcon,
      closable: false,
    },
    {
      id: 4,
      title: "数据",
      icon: tableIcon,
      closable: false,
    },
  ]);
  // 初始化字段数据（空数组，将从后端获取）
  const fields = ref<DynamicField[]>(
    mockFieldsProjectResponse.map((field) => ({
      ...field,
      // 确保options的value类型为string
      options: field.options
        ? field.options.map((option) => ({
            label: option.label,
            value: String(option.value),
            tag: option.tag,
          }))
        : undefined,
    })),
  );
  const routerFields = ref(["name"]);
  const dialogRouterFields = ref(["assignee", "startDate", "endDate"]);
  const moreActions = ref([]);
  const statusOptions = ref<Record<string, any>>({});
  const tableConfig = ref({
    editable: true,
    borderMode: "none",
    typeIconShow: true, // 列表表格是否显示类型图标
    // showOperationsColumn: true, // 是否显示操作列
    // OperationsColumnMode: "text", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 150, //自定义操作列宽度
    frozenColCount: 3, // 冻结前面列数
    rightFrozenColCount: 1, // 冻结后面列数
    tree: {
      enabled: true, // 开启树形结构
      column: 2, // 开启的树形结构的列索引
      mode: "wbs", // 开启wbs模式
    },
    rowSeriesNumber: {
      dragOrder: true, // 开启行号拖拽排序
    },

    widthMode: "adaptive", // 表格宽度模式
    enableCustomDrag: true,
    // borderMode: "none", // 表格边框模式，none为无边框
    page: {
      enable: true,
      pageSizes: [5, 10, 20, 50, 100],
      pageSize: 20,
      layout: "total, sizes, prev, pager, next, jumper",
    },
  });
  const ganttConfig = ref({
    ...tableConfig.value,
    mode: "gantt", // 开启甘特图
    showOperationsColumn: false,
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    taskListTable: {
      menu: {
        contextMenuItems: ["添加子记录", "删除"],
      },
      tableWidth: 458,
    },
    minDate: "2025/08/01",
    maxDate: "2025/12/31",
    enableCustomDrag: true,
    timelineHeader: {
      colWidth: 65,
    },
  });

  // 工具栏选项
  const toolbarOptions = ref({
    add: {
      name: "添加",
      enable: true,
    },
    fieldConfig: true,
    filter: true,
    sort: true,
    lineHeight: true,
    search: {
      name: "请输入任务名称搜索",
      enable: true,
    },
    // help: true,
    // log: true,
    // export: true,
  });

  // 字段配置弹窗相关状态
  const showFieldConfig = ref(false);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const currentFields = ref<DynamicField[]>([]);

  // 分页相关状态
  const pages = reactive<{
    page: number;
    pageSize: number;
    total: number;
    conditions: QueryCondition[];
    sortParams: SortParam[];
  }>({
    page: 1,
    pageSize: 20,
    total: 0,
    conditions: [],
    sortParams: [],
  });

  // 初始化表格数据，将从父组件传递给wbsTable
  const tableData = ref<ProjectNode[]>([]);
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high">("low");
  const tableLinks = ref<any[]>([]);
  const clTableRef = ref<InstanceType<typeof CLTable> | null>(null);
  // 用于存储用户选择的节点
  const selectedNodes = ref<ProjectNode[]>([]);

  // 处理节点选择事件
  const handleNodeSelected = (nodes: ProjectNode[]) => {
    selectedNodes.value = nodes;
  };
  const showCLBatchOpToolbarGantt = ref(false);
  // 从后端获取字段数据
  const fetchFields = async () => {
    try {
      // 调用真实的API获取表头配置
      // targetType 可以根据实际业务需求传入，例如 'TASK' 或 'WBS'
      const response = await getTableHeaderByTargetType("TASK_BASE_FIELD");
      const result = JSON.parse(response?.config || []);
      fields.value = result?.map((config: Record<string, any>) => {
        return {
          ...config,
          field: config?.code,
          name: config?.displayName,
          type: config?.type,
          invisible: !!config?.invisible,
          options: config?.options
            ? config.options.map((option: any) => ({
                label: option.label,
                value: String(option.value),
                tag: option.tag,
              }))
            : undefined,
        };
      });
      reportFields.value = JSON.parse(JSON.stringify(mockFields));
      statusOptions.value = getRandomOptionsInRange(optionsData, 1, 5);
    } catch (error) {
      console.error("获取字段数据失败:", error);
      reportFields.value = JSON.parse(JSON.stringify(mockFields));
    }
  };

  const route = useRoute();
  const currentProjectId =
    (route.params as any).projectId || (route.query as any).projectId || "";

  // 递归处理嵌套的name和children结构
  const processNestedData = (data: any): any => {
    if (!data) return data;

    if (Array.isArray(data)) {
      return data.map((item) => processNestedData(item));
    }

    if (typeof data === "object") {
      const processed = { ...data };

      // 处理name字段：将name['zh_CN']转换为name
      if (
        processed.name &&
        typeof processed.name === "object" &&
        processed.name["zh_CN"]
      ) {
        processed.name = processed.name["zh_CN"];
      }

      // 递归处理children字段
      if (processed.children && Array.isArray(processed.children)) {
        processed.children = processNestedData(processed.children);
      }

      return processed;
    }

    return data;
  };

  // 从后端获取表格数据
  const fetchTableData = async () => {
    try {
      // 调用真实的任务树API（返回 ProjectVORes[]）
      const response = await listTask(currentProjectId as string);

      // 处理返回的数据
      if (Array.isArray(response)) {
        const processedData = processNestedData(response);
        tableData.value = processedData;
        popupTable.value = JSON.parse(JSON.stringify(processedData));
        pages.total = processedData.length;
      } else {
        // 如果API调用失败，使用模拟数据作为后备
        console.warn("API返回数据格式异常，使用模拟数据");
        const dataWithDate = projectSampleData.map((item) => ({
          ...item,
          date: item.startDate || new Date().toISOString().split("T")[0],
        }));
        tableData.value = JSON.parse(JSON.stringify(dataWithDate));
        popupTable.value = JSON.parse(JSON.stringify(dataWithDate));
        // 获取数据报告页面的数据
        reportTableData.value = JSON.parse(JSON.stringify(mockData));
        // 获取数据报告页面的左侧菜单数据
        reportMenuData.value = JSON.parse(JSON.stringify(treeData));
        pages.total = projectSampleData.length;
      }

      // 更新甘特图链接数据
      tableLinks.value = JSON.parse(JSON.stringify(tmpLinks));
      if (clTableRef.value) {
        clTableRef.value.updateLinks(tableLinks.value);
      }
    } catch (error) {
      console.error("获取任务列表数据失败:", error);
      // 如果API调用失败，使用模拟数据作为后备
      console.warn("API返回数据格式异常，使用模拟数据");
      const dataWithDate = projectSampleData.map((item) => ({
        ...item,
        date: item.startDate || new Date().toISOString().split("T")[0],
      }));
      tableData.value = JSON.parse(JSON.stringify(dataWithDate));
      popupTable.value = JSON.parse(JSON.stringify(dataWithDate));
      pages.total = projectSampleData.length;
      // 获取数据报告页面的数据
      reportTableData.value = JSON.parse(JSON.stringify(mockData));
      // 获取数据报告页面的左侧菜单数据
      reportMenuData.value = JSON.parse(JSON.stringify(treeData));
    }

    // 更新甘特图链接数据
    tableLinks.value = JSON.parse(JSON.stringify(tmpLinks));
    if (clTableRef.value) {
      clTableRef.value.updateLinks(tableLinks.value);
    }
  };

  // 分页处理函数
  const pagerChange = (params: { currentPage: number; pageSize: number }) => {
    pages.page = params.currentPage;
    pages.pageSize = params.pageSize;
    fetchTableData();
  };

  // 添加节点的钩子函数
  const handleAddNode = (parentNode: ProjectNode, newNode: ProjectNode) => {
    console.log("添加节点:", parentNode, newNode);

    // 实际项目中，这里应该调用API保存数据
    // 例如: await axios.post('/api/wbs/add', { parentId: parentNode.id, node: newNode });

    // 这里仅作前端演示，实际添加逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理添加逻辑，可以在这里实现
  };

  // 删除节点的钩子函数
  const handleDeleteNode = (node: ProjectNode) => {
    console.log("删除节点:", node);

    // 实际项目中，这里应该调用API删除数据
    // 例如: await axios.delete('/api/wbs/delete', { params: { id: node.id } });

    // 这里仅作前端演示，实际删除逻辑由wbsTable组件内部处理
    // 如果需要在父组件中处理删除逻辑，可以在这里实现
  };

  // 更新节点的钩子函数
  const handleUpdateNode = async (
    node: ProjectNode,
    field: string,
    value: any,
  ) => {
    console.log("更新节点:", node, field, value);

    try {
      // 构建更新数据，将字段更新应用到节点数据
      const updatedNode = {
        ...node,
        [field]: value,
      };

      // 转换数据格式以匹配ProjectVORes接口
      const taskData = {
        ...updatedNode,
        // 确保name字段格式正确
        name:
          typeof updatedNode.name === "string"
            ? { zh_CN: updatedNode.name }
            : updatedNode.name,
      };

      // 调用API更新任务
      const response = await updateTask(taskData as any);
      console.log("任务更新成功:", response);

      // 更新本地数据
      updateRecord(updatedNode);
    } catch (error) {
      console.error("更新任务失败:", error);
      // 可以在这里添加错误提示
    }
  };

  // 更新表格数据的函数
  const updateTableData = (data: ProjectNode[]) => {
    console.log("表格数据更新:", data);
    tableData.value = data;
    // showAddRecordDialog.value = "0%";
    // 实际项目中，这里可以选择是否保存更新后的数据到后端
    // 例如: await axios.post('/api/wbs/save-all', data);
  };
  const updateRecord = (record: any) => {
    console.log("更新记录:", record);
    // 递归查找并更新节点
    const updateNodeById = (
      nodes: ProjectNode[],
      targetId: string,
      newData: any,
    ): boolean => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === targetId) {
          // 找到目标节点，更新数据
          nodes[i] = { ...nodes[i], ...newData };
          return true;
        }

        // 如果有子节点，递归查找
        if (nodes[i].children && nodes[i].children!.length > 0) {
          if (updateNodeById(nodes[i].children!, targetId, newData)) {
            return true;
          }
        }
      }
      return false;
    };
    // 在 tableData 中查找并更新记录
    updateNodeById(tableData.value, record.id, record);
  };
  // 更新字段可见性状态
  const updateFieldVisibility = (fieldId: number, invisible: boolean) => {
    const field = fields.value.find((f) => f.id === fieldId);
    if (field) {
      field.invisible = invisible;
    }
  };

  // 处理搜索事件
  const handleSearch = (keyword: string, searchFields?: string[]) => {
    console.log("搜索关键词:", keyword);
    console.log("搜索字段:", searchFields);

    // 设置搜索条件，参考project模块的QueryCondition结构
    pages.conditions = [
      {
        field: "name", // 默认搜索字段，可以根据实际需求调整
        operator: "=",
        value: keyword, // 使用project模块的value结构
      },
    ];

    // 重置到第一页
    pages.page = 1;

    // 调用API获取搜索结果
    fetchTableData();
  };

  // 处理排序事件
  const handleSort = (
    condition: DynamicField | null,
    direction: "asc" | "desc",
  ) => {
    console.log("排序条件:", condition, "排序方向:", direction);

    // 设置排序参数，参考project模块的SortParam结构
    if (condition) {
      const sortParams: SortParam[] = [
        {
          asc: direction === "asc",
          field: condition.field || condition.name,
        },
      ];
      pages.sortParams = sortParams;
    } else {
      pages.sortParams = [];
    }

    // 重置到第一页
    pages.page = 1;

    // 调用API获取排序结果
    fetchTableData();
  };

  // 处理筛选事件
  const handleFilter = (conditions: any[]) => {
    console.log("筛选条件:", conditions);

    // 将CToolbarWbs的FilterCondition转换为project模块的QueryCondition结构
    // const queryConditions: QueryCondition[] = (conditions || []).map(condition => ({
    //   field: condition.field,
    //   operator: condition.operator,
    //   value: condition.value, // 转换为project模块的value结构
    // }));

    pages.conditions = conditions;

    // 重置到第一页
    pages.page = 1;

    // 调用API获取筛选结果
    fetchTableData();
  };

  // 更新字段数据
  const updateField = (
    fieldId: number,
    updatedData: DynamicField & { options?: any[] },
  ) => {
    console.log("更新字段:", fieldId, updatedData);
    const field = fields.value.find((f) => f.id === fieldId);
    if (field) {
      Object.assign(field, updatedData);

      if (
        updatedData.options &&
        (field.type === "radio" || field.type === "multiple")
      ) {
        console.log(`更新字段"${field.name}"的选项，刷新表格数据`);
        // 创建一个新的数组引用
        tableData.value = [...tableData.value];
      }
    }
  };

  // 处理字段重排序事件
  const handleFieldReordered = (reorderedFields: DynamicField[]) => {
    console.log(
      "处理字段重排序:",
      reorderedFields.map((f) => f.name),
    );
    fields.value = [...reorderedFields];
  };

  // 标签页相关处理函数
  const handleTabAdded = (tab: TabItem) => {
    console.log("标签页添加:", tab);
  };

  const handleTabRemoved = (tab: TabItem) => {
    console.log("标签页移除:", tab);
  };

  const handleTabSorted = (tabs: TabItem[]) => {
    console.log("标签页排序:", tabs);
    tabItems.value = tabs;
  };
  const drawerDisplay = ref(false);
  const handleTabActivated = (tabId: number) => {
    console.log("标签页激活:", tabId);
    drawerDisplay.value = tabId !== 1;
  };

  // 处理行高变化事件
  const handleLineHeightChanged = (
    lineHeight: "low" | "medium" | "high" | "ultra-high",
  ) => {
    console.log("行高已变更为:", lineHeight);
    // 将ultra-high映射为high，因为CLTable组件不支持ultra-high
    currentLineHeight.value = lineHeight === "ultra-high" ? "high" : lineHeight;
  };
  const showAddRecordDialog = ref("0%");
  const handleAddRecordDialog = () => {
    console.log("添加记录");
    showAddRecordDialog.value = "65%";
    selectedRecord.value = null;
  };
  const closeRecordDialog = () => {
    showAddRecordDialog.value = "0%";
  };
  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };

  const addRecord = (newRecords: ProjectNode[]) => {
    tableData.value = [...newRecords];
  };

  // 提供给所有子孙组件使用
  provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);
  // 组件挂载时获取字段数据和表格数据
  onMounted(() => {
    fetchFields();
    fetchTableData();
  });

  // 批量操作相关状态
  const selectedRecords = ref<ProjectNode[]>([]);
  const showCLBatchOpToolbar = ref(false);

  const handleShowRecords = (records: ProjectNode[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
    showCLBatchOpToolbarGantt.value = records.length > 0;
  };

  // 处理批量删除操作
  const handleBatchDelete = () => {
    if (selectedRecords.value.length === 0) return;

    // 调用删除节点的函数处理批量删除
    selectedRecords.value.forEach((record) => {
      handleDeleteNode(record);
    });

    // 删除完成后清空选中状态
    selectedRecords.value = [];
    showCLBatchOpToolbar.value = false;
  };
  const selectedRecord = ref<ProjectNode | null>(null);
  const handleShowRecordDetail = (record: ProjectNode) => {
    selectedRecord.value = record;
    showAddRecordDialog.value = "65%";
  };

  const showBatchModifyDialog = ref(false);
  const batchModifyType = ref<"properties" | "type">("properties");
  const targetType = ref("");
  const batchModifyFields = ref<DynamicField[]>([]);

  const handleModifyProperties = () => {
    batchModifyType.value = "properties";
    showBatchModifyDialog.value = true;
    //获取选择数据的字段配置
    batchModifyFields.value = mockFieldsResponse as DynamicField[];
  };

  const handleModifyType = () => {
    batchModifyType.value = "type";
    targetType.value = "任务";
    showBatchModifyDialog.value = true;
  };

  const handleBatchModifyConfirm = (data: any) => {
    console.log("批量修改确认:", data);
    // 这里可以调用API执行批量修改操作
    // 示例：await api.batchModify(data);
    handleBatchModifyClose();
  };

  const handleBatchModifyCancel = () => {
    console.log("批量修改取消");
    handleBatchModifyClose();
  };
  const handleBatchModifyClose = () => {
    showBatchModifyDialog.value = false;
  };
  const popup = ref(false);
  const title = ref("");
  const neededFieldNames = ref();
  const popupTable = ref(tableData.value);
  const userTableConfig = ref({
    editable: false,
    tableH: "300px",
    typeIconShow: true, // 列表表格是否显示类型图标
    showOperationsColumn: false, // 是否显示操作列
    // OperationsColumnMode: "text", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 150, //自定义操作列宽度
    frozenColCount: 3, // 冻结前面列数
    rightFrozenColCount: 1, // 冻结后面列数
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    enableCustomDrag: false,
    // borderMode: "none", // 表格边框模式，none为无边框
    page: {
      enable: true,
    },
  });
  const selectorUserName = ref<string[]>();
  const changeNode = ref();
  //修改的用户名字
  const changeUserName = ref();
  //修改的字段名称
  const changeType = ref();
  // 处理更多操作
  const handleMoreAction = (
    action: string,
    node: ProjectNode | ProjectNode[],
    args?: any,
  ) => {
    console.log("handleMoreAction", action, node, args);
    if (action === "delete") {
      handleDeleteNode(node as ProjectNode);
    } else if (action === "view") {
      handleShowRecordDetail(node as ProjectNode);
    } else if (action === "linkDelete") {
      if (clTableRef.value) {
        clTableRef.value.deleteLink(node);
      }
    } else if (action === "change_cell_value") {
      console.log("change_cell_value", node);
      selectedRecord.value = node as ProjectNode;
      if (showAddRecordDialog.value !== "0%")
        handleShowRecordDetail(node as ProjectNode);
    } else if (action === "name") {
      if (showAddRecordDialog.value !== "0%")
        handleShowRecordDetail(node as ProjectNode);
    } else if (action === "userSelector") {
      popup.value = true;
      title.value = "选择用户";
      changeNode.value = node;
      changeType.value = (node as any)._fieldName;
      changeUserName.value = (node as ProjectNode)[changeType.value];
      neededFieldNames.value = ["name", "status", changeType.value];
      // console.log("handleSelectorNodes", node, neededFieldNames.value);
    } else if (action === "selectorUserName") {
      const nodes = Array.isArray(node) ? node : [node];
      if (nodes.length === 0) return;
      selectorUserName.value = nodes.map((node) => node[changeType.value]);
      console.log("handleSelectorNodes!!!", node, selectorUserName.value);
      changeNode.value[changeType.value] = selectorUserName.value;
      updateRecord(changeNode.value);
    } else if (action === "taskStatus") {
      statusOptions.value = getRandomOptionsInRange(optionsData, 1, 5);
      console.log("1111", statusOptions);
    }
  };
  const getRandomOptionsInRange = (
    options: typeof optionsData,
    min: number,
    max: number,
  ) => {
    const count = Math.floor(Math.random() * (max - min + 1)) + min;
    const shuffled = [...options].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, Math.min(count, options.length));
  };
  const currentViewMode = ref<"week" | "mouth">("week"); // 默认为周视图
  const changeColWidth = (mode: "week" | "mouth") => {
    currentViewMode.value = mode; // 更新当前选中模式
    if (mode === "week")
      ganttConfig.value = {
        ...ganttConfig.value,
        timelineHeader: {
          colWidth: 65,
        },
      };
    else
      ganttConfig.value = {
        ...ganttConfig.value,
        timelineHeader: {
          colWidth: 175,
        },
      };
  };
  const reportFields = ref();
  const reportTableData = ref();
  const reportMenuData = ref();
  const reportMoreActions = ref([
    { key: "edit", label: "编辑" },
    { key: "layoutSetting", label: "布局设置" },
    { key: "delete", label: "删除" },
  ]);
  const reportToolbarOptions = ref({
    search: {
      enable: true,
      name: "请输入名称搜索",
    },
  });
  const reportRouterFields = ref(["projectStatus", "assignAllTenant"]);
  const reportTableConfig = ref({
    editable: false,
    page: {
      enable: true,
    },
    widthMode: "adaptive", // 表格宽度模式
    selectionStyle: null, // 自定义选择样式
    tableH: "calc(100vh - 130px)",
    borderMode: "none",
    tree: { enabled: false },
    enableCustomDrag: false,
    OperationsColumnMode: "text", // 操作列模式，text为文本模式
    OperationsColumnWidth: 180, //自定义操作列宽度
    rowSeriesNumber: {},
  });

  const handleDragCompleted = (args: any) => {
    console.log("handleDragCompleted", args);
  };

  const cTableTaskRef = ref<InstanceType<typeof CLTable> | null>(null);
  // 切换drag
  const dragFn = async () => {
    tableConfig.value.rowSeriesNumber.dragOrder =
      !tableConfig.value.rowSeriesNumber.dragOrder;
  };
</script>

<style scoped>
  .wbs-container {
    background-color: #ffffff;
  }

  .wbs-tree-container {
    background-color: #fff;
    padding: 0 20px;
    position: relative;
  }

  .batch-btn {
    padding: 4px 12px;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 12px;
    color: #42464e;
  }

  .batch-btn:hover {
    color: #42464e;
    background-color: rgba(31, 35, 41, 0.1);
  }

  /* 滚动条样式 */
  .wbs-tree-container::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .wbs-tree-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;
  }

  .wbs-tree-container::-webkit-scrollbar-thumb:hover {
    background: #555;
  }
  .add-record-dialog-container {
    width: 0;
  }
  .gantt-time-btn {
    background-color: #fff;
    border: 0 solid #fff;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
    color: #42464e;
    width: 24px;
    height: 24px;
    font-weight: 500;
  }

  .gantt-time-btn:hover {
    color: #1aa1fb;
    background-color: #e8f1fb;
  }
  .gantt-time-btn.active {
    color: #1aa1fb;
    background-color: #e8f1fb;
    font-weight: 600;
  }
  .gantt-time-btns {
    display: flex;
    align-items: center;
    position: absolute;
    top: 9px;
    right: 24px;
    z-index: 10;
  }
</style>
<style lang="scss">
  .table-container {
    .el-select__wrapper {
      box-shadow: none !important;
      font-size: 12px;
    }
    .el-select-dropdown__item {
      font-size: 12px;
    }
  }
</style>
